<template>
    <div :class="['gotop-wrap', activeClass]" @click="handleTop">
        <img class="img" src="@/assets/images/gotop.png" alt="返回顶部" />
    </div>
</template>

<script>
import { onBeforeUnmount, onMounted, ref } from 'vue'
export default {
    name: 'GoTop',
    setup() {
        const activeClass = ref('')
        const handleTop = () => {
            const doc = document.scrollingElement
            Math.easeout(doc.scrollTop, 0, 4, function (value) {
                doc.scrollTop = value
            })
        }
        const scrollFn = () => {
            // A 起始位置 B目标位置 rate缓动速率
            Math.easeout = function (A, B, rate, callback) {
                if (A === B || typeof A !== 'number') {
                    return  
                }
                B = B || 0
                rate = rate || 2
                
                const step = function () {
                    A = A + (B - A) / rate
                    
                    if (A < 1) {
                        callback(B, true)
                        return
                    }
                    callback(A, false)
                    requestAnimationFrame(step)   
                }
                step()
            }
        }

        const listenScroll = () => {
            const st = document.scrollingElement.scrollTop
            const cls = st > 200 ? 'active' : ''
            activeClass.value = cls
        }

        onMounted(() => {
            scrollFn()
            window.addEventListener('scroll', listenScroll)
        })

        onBeforeUnmount(() => {
            window.removeEventListener('scroll', listenScroll)
        })
        
        return {
            activeClass,
            handleTop
        }
    }
}
</script>

<style lang="scss" scoped>
    .gotop-wrap {
        position: fixed;
        right: 10px;
        bottom: 20px;
        z-index: 2;
        transform: translate3d(100%, 100%, 0);
        transition: transform .3s ease-in-out;
        filter: drop-shadow(1px 1px 5px rgba(0,0,0,.5));
        &:focus,&:active{
            opacity: 0.8;
        } 
        &.active{
            transform: translate3d(0, 0, 0);
        }
        .img {
            width: 52px;
            height: 52px;
        }
    }    
</style>